package cn.itcast.interceptor;

import cn.itcast.util.Result;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //用户重置登录 系统需要给浏览器发送一个token
        //浏览器接受这个token，并记录下来
        //之后浏览器每次发送请求都需要这个token 将token放到Header中 如果有token就是登录过的 如果没有就是没有登陆过
        //在拦截器中拦截每个请求，获取Header中的token 如果获取到就执行，没有就截至

        String token=request.getHeader("authentication");
        if(token==null||token.isEmpty()){
            Result result=Result.fail(401,"认证失败");
            //需要转换json格式
            String json= JSON.toJSONString(result);
            response.getWriter().write(json);
            return false;

        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
